(function() {
    // 检查是否已经存在 WebSocket 实例
    if (!window.socket) {
        // 获取当前页面的协议（http 或 https）
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        // 获取当前页面的主机名和端口号
        const host = window.location.host;
        // 构造 WebSocket 地址
        const socketUrl = `${protocol}//${host}/ws/user-status`;
        // 创建 WebSocket 连接
        window.socket = new WebSocket(socketUrl);

        // 监听连接关闭
        window.socket.onclose = function() {
            console.log('WebSocket 连接已关闭');
            delete window.window; // 清除实例，以便重新连接
        };

        // 监听 WebSocket 消息
        window.socket.onmessage = function (event) {
            const data = JSON.parse(event.data);

            const online = "<span class=\"badge bg-success\">在线</span>"
            const offline = "<span class=\"badge bg-danger\">离线</span>"
            // 查找表格中对应的行并更新
            const rows = document.querySelectorAll('#status-table-body tr');
            for (const row of rows) {
                const usernameCell = row.querySelector('td:first-child');
                if (usernameCell.textContent === data.username) {
                    // 更新拉手端
                    const handshakeCell = row.querySelector('td:nth-child(3)');
                    handshakeCell.innerHTML = data.handshakeConnected ? online : offline;

                    // 更新插卡端
                    const cardCell = row.querySelector('td:nth-child(4)');
                    cardCell.innerHTML = data.cardConnected ? online : offline;

                    // 更新语音端
                    const voiceCell = row.querySelector('td:nth-child(5)');
                    voiceCell.innerHTML = data.voiceConnected ? online : offline;

                    break;
                }
            }
            // 更新总账号数和在线用户数
            document.getElementById('all-users-count').textContent = data.allUsersCount;
            document.getElementById('online-users-count').textContent = data.onlineUsersCount;
        };

        // 监听错误
        window.socket.onerror = function(error) {
            console.error('WebSocket 错误:', error);
        };
    }

    let currentPage = 0; // 当前页码
    const pageSize = 10; // 每页大小
    let currentMode = "all"; // 默认显示所有用户

    // 获取用户在线状态并更新表格
    window.fetchOnlineUsers = function fetchOnlineUsers(page) {
        currentMode = "online"; // 更新当前模式为在线用户
        fetch(`/api/status/online-users?page=${page}&size=${pageSize}`)
            .then(response => response.json())
            .then(data => {
                const tableBody = document.getElementById('status-table-body');
                tableBody.innerHTML = ''; // 清空表格内容

                const online = "<span class=\"badge bg-success\">在线</span>"
                const offline = "<span class=\"badge bg-danger\">离线</span>"
                // 遍历用户状态数据，生成表格行
                data.content.forEach(user => {
                    const row = document.createElement('tr');

                    // 用户名列
                    const usernameCell = document.createElement('td');
                    usernameCell.textContent = user.username;
                    row.appendChild(usernameCell);

                    // 密码列
                    const passwordCell = document.createElement('td');
                    passwordCell.textContent = user.password;
                    row.appendChild(passwordCell);

                    // 拉手端列
                    const handshakeCell = document.createElement('td');
                    handshakeCell.innerHTML = user.handshakeConnected ? online : offline;
                    row.appendChild(handshakeCell);

                    // 插卡端列
                    const cardCell = document.createElement('td');
                    cardCell.innerHTML = user.cardConnected ? online : offline;
                    row.appendChild(cardCell);

                    // 语音端列
                    const voiceCell = document.createElement('td');
                    voiceCell.innerHTML = user.voiceConnected ? online : offline;
                    row.appendChild(voiceCell);

                    // 添加到表格
                    tableBody.appendChild(row);
                });
                // 更新分页控件
                updatePagination(data.totalPages, page, fetchOnlineUsers);
                // 更新总账号数和在线用户数
                document.getElementById('all-users-count').textContent = data.allUsersCount;
                document.getElementById('online-users-count').textContent = data.onlineUsersCount;
            })
            .catch(error => {
                console.error('Error fetching online users:', error);
                showToast('无法获取在线状态，请检查网络连接！');
            });
    }

    window.fetchAllUsers = function fetchAllUsers(page) {
        currentMode = "all"; // 更新当前模式为所有用户
        fetch(`/api/status/all-users?page=${page}&size=${pageSize}`)
            .then(response => response.json())
            .then(data => {
                const tableBody = document.getElementById('status-table-body');
                tableBody.innerHTML = ''; // 清空表格内容

                const online = "<span class=\"badge bg-success\">在线</span>"
                const offline = "<span class=\"badge bg-danger\">离线</span>"
                // 遍历用户状态数据，生成表格行
                data.content.forEach(user => {
                    const row = document.createElement('tr');

                    // 用户名列
                    const usernameCell = document.createElement('td');
                    usernameCell.textContent = user.username;
                    row.appendChild(usernameCell);

                    // 密码列
                    const passwordCell = document.createElement('td');
                    passwordCell.textContent = user.password;
                    row.appendChild(passwordCell);

                    // 拉手端列
                    const handshakeCell = document.createElement('td');
                    handshakeCell.innerHTML = user.handshakeConnected ? online : offline;
                    row.appendChild(handshakeCell);

                    // 插卡端列
                    const cardCell = document.createElement('td');
                    cardCell.innerHTML = user.cardConnected ? online : offline;
                    row.appendChild(cardCell);

                    // 语音端列
                    const voiceCell = document.createElement('td');
                    voiceCell.innerHTML = user.voiceConnected ? online : offline;
                    row.appendChild(voiceCell);

                    // 添加到表格
                    tableBody.appendChild(row);
                });

                // 更新分页控件
                updatePagination(data.totalPages, page, fetchAllUsers);
                // 更新总账号数和在线用户数
                document.getElementById('all-users-count').textContent = data.allUsersCount;
                document.getElementById('online-users-count').textContent = data.onlineUsersCount;
            })
            .catch(error => {
                console.error('Error fetching online users:', error);
                showToast('无法获取在线状态，请检查网络连接！');
            });
    }

    fetchAllUsers(currentPage)
})();
